package com.oe.test.controller;

import com.oe.mvc.Interceptor.LdmInterceptor;
import com.oe.mvc.annotation.Interceptor;
import com.oe.mvc.handler.Handler;
import com.oe.test.annotation.Security;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

@Interceptor
public class SecurityInterceptor implements LdmInterceptor {

    @Override
    public boolean preHnadle(HttpServletRequest req, HttpServletResponse resp, Handler handler) {
        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] usernames = parameterMap.get("name");
        String username = usernames[0];
        boolean flag=false;
        if(handler==null||handler.getController()==null){
            try {
                resp.getWriter().write("404");
                return false;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Class<?> aClass = handler.getController().getClass();
        boolean annotationPresent =aClass .isAnnotationPresent(Security.class);
        if(annotationPresent){
            Security annotation = aClass.getAnnotation(Security.class);
            String[] value = annotation.value();
            if(value!=null){
                for (String name : value) {
                    if(name.equals(username)){
                        flag=true;
                        break;
                    }
                }
            }
        }
        if (!flag){
            Method method = handler.getMethod();
            if(method.isAnnotationPresent(Security.class)){
                Security annotation = method.getAnnotation(Security.class);
                String[] value = annotation.value();
                if(value!=null){
                    for (String s : value) {
                        if(s.equals(username)){
                            flag=true;
                            break;
                        }
                    }
                }
            }
        }
        if(!flag){
            try {
                req.getRequestDispatcher("authority").forward(req,resp);
                return false;
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public boolean doHnadle(HttpServletRequest req, HttpServletResponse resp, Handler handler) {
        return true;
    }

    @Override
    public boolean afterHnadle(HttpServletRequest req, HttpServletResponse resp, Handler handler) {
        return true;
    }
}
